<template>
  <div>
    <!-- Breadcrumb 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入搜索内容"
            v-model="queryInfo.query"
            clearable
            @clear="getuserlist()"
          >
            <el-button slot="append" icon="el-icon-search" @click="getuserlist"></el-button>
          </el-input>
          <div class="grid-content bg-purple"></div>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="adddialogVisible=true">添加用户</el-button>
          <div class="grid-content bg-purple"></div>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table border stripe style="width: 100%" :data="userlist">
        <el-table-column type="index" :index="index"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <!-- {{scope.row.id}} -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              size="min"
              @click="modifydialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              size="min"
              @click="deleteform(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-star-off"
                circle
                size="min"
                @click="roleedit(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[ 2,3,6,10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="adddialogVisible" width="50%" @close="adddialogClose">
      <el-form :model="addForm" :rules="addrules" ref="addRefs" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="ismodifydialog" width="50%" @close="modifydialogClose">
      <!-- 修改用户表单 -->
      <el-form
        ref="modifyRefs"
        :model="modifyForm"
        label-width="80px"
        size="mini"
        :rules="modifyFormRules"
      >
        <el-form-item label="用户名">
          <el-input v-model="modifyForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="modifyForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="modifyForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <!-- {{modifyForm.id}} -->
        <el-button @click="ismodifydialog = false">取 消</el-button>
        <el-button type="primary" @click="modifyuser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="roleVisible" width="50%" @closed='roleClosed'>
      <div>当前的用户:{{userInfo.username}}</div>
      <div>当前的角色:{{userInfo.role_name}}</div>
      <div>
        分配新角色:
        <el-select v-model="newRole" placeholder="请选择">
          <el-option
            v-for="item in roleslist"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="roleVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveroles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkemail = (rule, value, callback) => {
      const regemail = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
      if (regemail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    // 验证手机号的规则
    var checkmobile = (rule, value, callback) => {
      const regmobile = /0?(13|14|15|17|18|19)[0-9]{9}/;
      if (regmobile.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的手机号"));
    };
    return {
      // 获取用户列表对象
      queryInfo: {
        // 搜索关键字
        query: "",
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      userlist: [],
      total: 0,
      value: true,
      // 添加用户列表默认不显示
      adddialogVisible: false,
      // 修改用户列表默认不显示
      ismodifydialog: false,
      // 添加用户的表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      modifyForm: {},
      // 添加用户表单验证规则
      addrules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur"
          },
          {
            min: 3,
            max: 10,
            message: "用户名长度在3~10字符之间",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur"
          },
          {
            min: 6,
            max: 15,
            message: "用户名长度在6~15字符之间",
            trigger: "blur"
          }
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur"
          },
          {
            validator: checkemail,
            trigger: "blur"
          }
        ],
        mobile: [
          {
            message: "请输入手机号",
            required: true,
            trigger: "blur"
          },
          {
            validator: checkmobile,
            trigger: "blur"
          }
        ]
      },
      modifyFormRules: {
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur"
          },
          {
            validator: checkemail,
            trigger: "blur"
          }
        ],
        mobile: [
          {
            message: "请输入手机号",
            required: true,
            trigger: "blur"
          },
          {
            validator: checkmobile,
            trigger: "blur"
          }
        ]
      },
      // 分配角色对话框
      roleVisible: false,
      userInfo: "",
      roleslist: "",
      newRole:''
    };
  },
  created() {
    this.getuserlist();
  },
  methods: {
    async getuserlist() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      }
      this.userlist = res.data.users;
      this.total = res.data.total;
      //   console.log(this.userlist);
    },
    // 监听pagesize改变的事件
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize;
      this.getuserlist();
    },
    // 监听页码值改变的事件
    handleCurrentChange(newpage) {
      // console.log(newpage);
      this.queryInfo.pagenum = newpage;
      this.getuserlist();
    },
    async userStateChanged(userinfo) {
      // console.log(userinfo);
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("用户更新数据失败");
      }
      this.$message.success("用户更新成功");
      // console.log(res);
    },

    // userStateChanged(userinfo){
    //   console.log(userinfo);
    // const res=this.$http.put('users/${userinfo.id}/state/${userinfo.ma_state}')
    // console.log(res);

    // }
    // add(){
    //   this.$http.post('users',{
    //     username:queryInfo.query,
    //     password:
    //   })
    // }
    adddialogClose() {
      this.$refs.addRefs.resetFields();
    },
    addUser() {
      this.$refs.addRefs.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.addForm);
        //  console.log(res);
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败");
        }
        this.$message.success("添加用户成功");
        this.adddialogVisible = false;
        this.getuserlist();
        // console.log(valid);
      });
    },
    // 修改用户点击事件
    async modifydialog(id) {
      this.ismodifydialog = true;
      const { data: res } = await this.$http.get("users/" + id, {
        params: { id: id }
      });
      if (res.meta.status !== 200) {
        return this.$message.error("查询用户信息失败");
      }
      this.modifyForm = res.data;
      // console.log(res);
    },
    // 修改用户
    modifyuser() {
      this.$refs.modifyRefs.validate(async valid => {
        if (!valid) {
          return;
        }
        // console.log(valid);
        const { data: res } = await this.$http.put(
          "users/" + this.modifyForm.id,
          {
            email: this.modifyForm.email,
            mobile: this.modifyForm.mobile
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("更新用户失败");
        }
        this.$message.success("更新用户成功");
        // 关闭对话框
        this.ismodifydialog = false;
        // 刷新用户列表
        this.getuserlist();
        // console.log(res);
      });
      // const { data: res } = await this.$http.put("users/" + id);
      // if (res.meta.status !== 200) {
      //   return this.$message.error("更新用户失败");
      // }
      // this.$message.success("更新用户成功");
      // this.ismodifydialog = false;
      // this.getuserlist();
      // console.log(res);
    },
    modifydialogClose() {
      this.$refs.modifyRefs.resetFields();
    },
    // 删除表单提示框
    deleteform(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("users/" + id);
          if (res.meta.status !== 200) {
            return this.$message.error("删除用户失败");
          }
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.getuserlist();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async roleedit(userInfo) {
      this.roleVisible = true;
      // console.log(userInfo);
      this.userInfo = userInfo;
      // 获取角色列表
      const { data: res } = await this.$http.get("roles");
      console.log(res);
      this.roleslist = res.data;
    },
   async saveroles(){
      if(!this.newRole){
      return  this.$message.error('请选择新的角色')
      }
     const {data:res}=await this.$http.put(`users/${this.userInfo.id}/role`,{
        rid:this.newRole
      })
      if(res.meta.status!==200){
       return this.$message.error('用户更新失败')
      }
    this.$message.success('用户更新成功')
      console.log(res);
    this.roleVisible=false 
    this.getuserlist();
    },
    roleClosed(){
      this.newRole=''
      this.userInfo=''
    }
  },
  computed: {
    index() {
      return (this.queryInfo.pagenum - 1) * this.queryInfo.pagesize + 1;
    }
  }
};
</script>
<style lang="less" scoped>
// .el-input{
//     width: 50%;
//     margin-right: 10px;
// }
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
</style>